#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <queue>

using namespace std;

const int MAXN = 40;

int m, u, v;
int p;

struct Edge {
    int to, next;
} e[MAXN << 1];

int head[MAXN], idx = 1;

void add_edge(int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx++;
}
void clear_graph() {
    memset(head, -1, sizeof(head));
    memset(e, 0, sizeof(e));
    idx = 1;
}

int bfs(string st) {
    queue<string> q;

    map<string, int> d;

    d[st] = 0;
    string end = "#123456780";
    q.push(st);

    while (q.size()) {
        string t = q.front();
        q.pop();

        int dis = d[t];
        if (t == end) {
            return dis;
        }
        int pos = t.find('0');

        for (int i = head[pos]; ~i; i = e[i].next) {
            int j = e[i].to;
            swap(t[j], t[pos]);
            if (d.count(t) == 0) {
                d[t] = dis + 1;
                q.push(t);
            }
            swap(t[j], t[pos]);
        }
    }
    return -1;

}
int main() {
    cin >> m;
    clear_graph();

    for (int i = 1; i <= m; i++) {
        cin >> u >> v;
        add_edge(u, v);
        add_edge(v, u);
    }

    string state = "#000000000";
    for (int i = 1; i <= 8; i++) {
        cin >> p;
        state[p] = i + '0';
    }
    int res = bfs(state);
    cout << res << endl;

    return 0;
}